package com.zhuiyun.project.api.system.login.service.impl;

import com.google.gson.Gson;
import com.zhuiyun.project.api.collectVideo.model.FavoritesModel;
import com.zhuiyun.project.api.collectVideo.service.FavoritesService;
import com.zhuiyun.project.api.frontuser.entity.FrontUser;
import com.zhuiyun.project.api.frontuser.service.FrontUserService;
import com.zhuiyun.project.api.system.login.model.LoginDTO;
import com.zhuiyun.project.common.errorCode.CommonException;
import com.zhuiyun.project.common.response.CommonResult;
import org.springframework.beans.factory.annotation.Value;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.Date;
import java.util.UUID;

/**
 * @ClassName UserInfoService
 * @Description TODO
 * @Author 雅俗共赏
 * @Date 2024/2/27 13:53
 **/
@Service
@Slf4j
public class FrontUserInfoService {
    @Autowired
    private FrontUserService frontUserService;
    @Value("${APPID}")
    private String appid;
    @Value("${APPSECRET}")
    private String appsecret;
    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    public FavoritesService favoritesService;
    //Spring Security框架提供的一种密码加密工具，用于对密码进行哈希加密，提高密码的安全性。
    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;
    /**
     * 微信登录验证
     * @param code 临时登录码
     */
    public FrontUser checkLogin(String code) {
        String openid=frontUserService.CodeOpen(code);
        if(openid==null){
            System.out.println("登录时：uniapp传过来的code无法获取到openid。请检测前后端APPID是否一致。openid为="+openid);
            return null;
        }else{
            // 判断用户是否存在，查询数据库
            FrontUser frontUsers = frontUserService.getFrontUserByOpenId(openid);
            if(frontUsers==null){
                return null;
            }else{
                return frontUsers;
            }
        }

    }
    /**
     * 生成账号
     * @param length 指定账号长度
     */
    public String  GenerateAccount(int length) {
        StringBuilder sb = new StringBuilder();
        while (sb.length() < length) {
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            for (char c : uuid.toCharArray()) {
                if (Character.isDigit(c) && sb.length() < length) {
                    sb.append(c);
                }
            }
        }
        return sb.toString().substring(0, length);
    }
    /**
     * 微信注册
     * @param code 临时登录码
     */
    public CommonResult wxRegistration(String code) throws CommonException {
        String openid=frontUserService.CodeOpen(code);
        System.out.println("注册时：uniapp传过来的code无法获取到openid。请检测前后端APPID是否一致。openid为="+openid);
        if(openid==null){
            return CommonResult.error(500,"无法获取用户信息，请先登录微信");
        }else {
            // 判断用户是否存在，查询数据库
            FrontUser frontUsers = frontUserService.getFrontUserByOpenId(openid);
            // 不存在，加入数据表
            if(frontUsers==null){
                // 填充初始信息
                FrontUser frontUser = new FrontUser();
                frontUser.setWxOpenid(openid);//微信用户的唯一标识
                frontUser.setUserName("微信用户");//用户名称
                frontUser.setUserAccount(GenerateAccount(10));//用户账号
                frontUser.setUserPassword(bCryptPasswordEncoder.encode("123456"));//加密
                frontUser.setSex(1);//性别
                frontUser.setDelFlag(0);//用户是否删除
                frontUser.setSignature("编辑个性签名");//签名
                frontUser.setFans(0L);//粉丝数量
                frontUser.setLikes(0L);//被赞数量
                frontUser.setFollowWithInterest(0L);//关注数量
                frontUser.setBirthday(new Date());//生日
                frontUser.setBriefIntroduction("编辑个人简介");//个人简介
                frontUser.setAvatarId("http://101.43.223.224:8765/image/getImageById?id=6934");//头像
                frontUser.setCreateTime(new Date());
                // 加入数据表
                if(frontUserService.insertFrontUser(frontUser)){
                    FrontUser frontUserByOpenId = frontUserService.getFrontUserByOpenId(openid);
                    FavoritesModel favoritesModel =new FavoritesModel();
                    favoritesModel.setUserId(frontUserByOpenId.getId());
                    favoritesModel.setFavoName("默认收藏夹");
                    favoritesService.addFavorite(favoritesModel);
                    return CommonResult.ok("注册成功");
                }else{
                    return CommonResult.ok("注册未成功");
                }
            }else{
                return CommonResult.error("用户已存在，注册失败");
            }
        }
    }
    /**
     * 微信绑定用户
     * 根据code查询是否有微信绑定过账户
     * @param code 临时登录码
     */
    public String checkLogin2(String code) {
        // 根据传入code，调用微信服务器，获取唯一openid 微信服务器接口地址
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+ "&secret="+appsecret
                +"&js_code="+ code +"&grant_type=authorization_code";
        String openid = "";
        LoginDTO loginDTO;
        // 发送请求
        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.GET, null, String.class);
        // 判断请求是否成功
        if(responseEntity.getStatusCode() == HttpStatus.OK) {
            // 获取主要内容
            String sessionData = responseEntity.getBody();
            Gson gson = new Gson();
            //将json字符串转化为实体类;
            loginDTO = gson.fromJson(sessionData, LoginDTO.class);
            //获取用户的唯一标识openid
            openid = loginDTO.getOpenid();
        }
        // 判断用户是否存在，查询数据库
        FrontUser frontUsers = frontUserService.getFrontUserByOpenId(openid);
        // 不存在，加入数据表
        if(frontUsers==null){
            return openid;
        }else{
            return null;
        }

    }
}
